import { getUserInfo } from '@/api/user'
import { createStore, ActionContext } from 'vuex'
import { removeToken } from '@/utils/auth'

interface State {
  loginModalShow: boolean
  isLogin: boolean
  userInfo: any
}

const store = {
  state: {
    loginModalShow: false,
    isLogin: false,
    userInfo: {},
  },
  mutations: {
    showLogin(state: State) {
      state.loginModalShow = true
      console.log('state.loginModalShow: ', state.loginModalShow)
    },
    hideLogin(state: State) {
      state.loginModalShow = false
    },
    login(state: State) {
      state.isLogin = true
    },
    logout(state: State) {
      state.isLogin = false
      removeToken()
    },
    setUserInfo(state: State, userInfo: any) {
      state.userInfo = userInfo
    }
  },
  actions: {
    getUserInfo({ commit }: ActionContext<State, State>) {
      getUserInfo().then((res) => {
        console.log('res: ', res);
        if (res) {
          commit('login')
          commit('setUserInfo', res)
        }
      })
    }
  },
  getters: {
    loginModalShow(state: State) {
      return state.loginModalShow
    },
    isLogin(state: State) {
      return state.isLogin
    },
    userInfo(state: State) {
      return state.userInfo
    }
  },
}

export default createStore(store)
